import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { query } from 'common/src/config/database';
import bcrypt from 'bcryptjs';

// 用户登录
export const login = async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body;

    // 查找用户
    const [users] = await query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    const user = users[0];

    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 生成 token
    const token = jwt.sign(
      { userId: user.id, role: user.role },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '7d' }
    );

    res.json({
      success: true,
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          role: user.role
        }
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '登录失败'
    });
  }
};

// 获取用户信息
export const getUserInfo = async (req: Request, res: Response) => {
  try {
    const [users] = await query(
      'SELECT id, username, role, created_at FROM users WHERE id = ?',
      [req.user.userId]
    );
    const user = users[0];

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: user
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
};

// 更新用户信息
export const updateUserInfo = async (req: Request, res: Response) => {
  try {
    const { password } = req.body;
    
    if (password) {
      const hashedPassword = await bcrypt.hash(password, 10);
      await query(
        'UPDATE users SET password = ? WHERE id = ?',
        [hashedPassword, req.user.userId]
      );
    }

    const [users] = await query(
      'SELECT id, username, role, created_at FROM users WHERE id = ?',
      [req.user.userId]
    );
    const user = users[0];

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: user
    });
  } catch (error) {
    console.error('更新用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '更新用户信息失败'
    });
  }
}; 